﻿using Microsoft.OpenApi.Models;

namespace Future.Web.Extensions
{
    /// <summary>
    /// Swagger扩展
    /// </summary>
    public static class SwaggerExtension
    {
        /// <summary>
        /// 注册swagger服务
        /// </summary>
        /// <param name="services"></param>
        /// <returns></returns>
        public static IServiceCollection AddSwaggerService(this IServiceCollection services)
        {
            OpenApiInfo apiInfo = new()
            {
                Title = "api接口",
                Version = "v1"
            };

            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", apiInfo);

                //添加注释服务
                //为 Swagger JSON and UI设置xml文档注释路径
                //获取应用程序所在目录(绝对路径，不受工作目录影响，建议采用此方法获取路径使用windwos&Linux）
                string basePath = Path.GetDirectoryName(typeof(Program).Assembly.Location) ?? string.Empty;
                string apiXmlPath = Path.Combine(basePath, @"ApiSwaggerDoc.xml");//控制器层注释
                string entityXmlPath = Path.Combine(basePath, @"ModelSwaggerDoc.xml");//实体注释
                c.IncludeXmlComments(apiXmlPath, true);//true表示显示注释
                c.IncludeXmlComments(entityXmlPath, true);

                c.AddSecurityDefinition("JwtBearer", new OpenApiSecurityScheme()
                {
                    Description = "直接输入Token即可",
                    Name = "Authorization",
                    In = ParameterLocation.Header,
                    Type = SecuritySchemeType.Http,
                    Scheme = "bearer"
                });
                OpenApiSecurityScheme scheme = new()
                {
                    Reference = new OpenApiReference() { Type = ReferenceType.SecurityScheme, Id = "JwtBearer" }
                };
                c.AddSecurityRequirement(new OpenApiSecurityRequirement()
                {
                    [scheme] = Array.Empty<string>()
                });
            });

            return services;
        }

        /// <summary>
        /// 添加swagger中间件
        /// </summary>
        /// <param name="app"></param>
        public static void UseSwaggerAPI(this IApplicationBuilder app)
        {
            //在 Startup.Configure 方法中，启用中间件为生成的 JSON 文档和 Swagger UI 提供服务：
            app.UseSwagger();

            app.UseSwaggerUI(c =>
            {
                c.SwaggerEndpoint("/swagger/v1/swagger.json", "Future.Web");
            });
        }
    }
}
